package com.sunday.pinxinghui;


import android.content.Intent;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.TextView;
import android.widget.Toast;

import com.igexin.sdk.PushManager;
import com.sunday.common.base.BaseActivity;
import com.sunday.common.common.MemberConst;
import com.sunday.common.event.EventBus;
import com.sunday.common.event.ExitApp;
import com.sunday.common.model.ResultDO;
import com.sunday.common.model.Version;
import com.sunday.common.update.UpdateDialogActivity;
import com.sunday.common.utils.Constants;
import com.sunday.common.utils.DeviceUtils;
import com.sunday.common.utils.SharePerferenceUtils;
import com.sunday.common.utils.StatusBarUtil;
import com.sunday.common.utils.ToastUtils;
import com.sunday.pinxinghui.base.BaseApplication;
import com.sunday.pinxinghui.base.MyBaseActivity;
import com.sunday.pinxinghui.entity.Member;
import com.sunday.pinxinghui.entity.Nums;
import com.sunday.pinxinghui.event.UpdateCartNum;
import com.sunday.pinxinghui.model.login.LoginActivity;
import com.sunday.pinxinghui.model.main.CartFragment;
import com.sunday.pinxinghui.model.main.ClassifyFragment;
import com.sunday.pinxinghui.model.main.IndexFragment;
import com.sunday.pinxinghui.model.main.LiveCircleFragment;
import com.sunday.pinxinghui.model.main.MineFragment;
import com.sunday.pinxinghui.network.ApiClient;
import com.sunday.pinxinghui.push.PushIntentService;
import com.sunday.pinxinghui.push.PushService;

import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import q.rorbin.badgeview.Badge;
import q.rorbin.badgeview.QBadgeView;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;


public class MainActivity extends MyBaseActivity {

    @Bind({R.id.tab1, R.id.tab2, R.id.tab3, R.id.tab4, R.id.tab5})
    List<TextView> tabViews;

    private Fragment[] fragments;
    private IndexFragment indexFragment;
    private int index;
    private int currentTabIndex;
    private Member member;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ButterKnife.bind(this);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            getWindow()
                    .getDecorView()
                    .setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_STABLE | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
        } else {
            getWindow()
                    .setFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS, WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        }
        checkLogin();

    }


    private void checkUpdate() {
        Call<ResultDO<Version>> call = ApiClient.getApiAdapter().checkVersion(DeviceUtils.getVersionCode(getApplicationContext()), 1);
        call.enqueue(new Callback<ResultDO<Version>>() {
            @Override
            public void onResponse(Call<ResultDO<Version>> call, Response<ResultDO<Version>> response) {
                ResultDO<Version> resultDO = response.body();
                if (isFinish) {
                    return;
                }
                if (resultDO != null && resultDO.getCode() == 0) {
                    final Version version = resultDO.getResult();
                    new Handler().postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            Intent intent = new Intent(mContext, UpdateDialogActivity.class);
                            intent.putExtra("version", version);
                            startActivity(intent);
                        }
                    }, 2000);
                }
            }

            @Override
            public void onFailure(Call<ResultDO<Version>> call, Throwable t) {

            }
        });
    }

    Badge badge;

    private void getCartsNum() {
        Call<ResultDO<Nums>> call = ApiClient.getApiAdapter().getCartsNum(member.getId());
        call.enqueue(new Callback<ResultDO<Nums>>() {
            @Override
            public void onResponse(Call<ResultDO<Nums>> call, Response<ResultDO<Nums>> response) {
                if (isFinish || response.body() == null) {
                    return;
                }
                if (response.body().getCode() == 0) {
                    if (badge == null) {
                        badge = new QBadgeView(mContext).bindTarget(tabViews.get(3)).setBadgeNumber(response.body().getResult().getNum());
                    } else {
                        badge.setBadgeNumber(response.body().getResult().getNum());
                    }
                    badge.setShowShadow(false);
                    badge.setBadgeBackground(ContextCompat.getDrawable(mContext, R.color.main_color), true);
                    badge.setBadgeGravity(Gravity.END | Gravity.TOP);
                    badge.setGravityOffset(8, 0, true);
                    badge.setBadgeTextSize(9, true);
                }
            }

            @Override
            public void onFailure(Call<ResultDO<Nums>> call, Throwable t) {
                ToastUtils.showToast(mContext, R.string.network_error);
            }
        });
    }


    private void checkLogin() {
        boolean login = SharePerferenceUtils.getIns(mContext).getBoolean(Constants.IS_LOGIN, false);
        if (!login) {
            intent = new Intent(mContext, LoginActivity.class);
            startActivity(intent);
            finish();
        } else {
            member = (Member) SharePerferenceUtils.getIns(mContext).getOAuth();
            if (member != null) {
                BaseApplication.getInstance().setMember(member);
                initFragments();
                checkSdCardPermission();
                checkLocationPermission();
                checkUpdate();
                //getCartsNum();
            } else {
                intent = new Intent(mContext, LoginActivity.class);
                startActivity(intent);
                finish();
            }
        }

    }

    private void initFragments() {
        indexFragment = IndexFragment.newInstance();
        ClassifyFragment mClassifyFragment = ClassifyFragment.newInstance();
        LiveCircleFragment mLiveCircleFragment = LiveCircleFragment.newInstance();
        CartFragment mCartFragment = CartFragment.newInstance(false);
        MineFragment mineFragment = MineFragment.newInstance();
        fragments = new Fragment[]{
                indexFragment,
                mClassifyFragment,
                mLiveCircleFragment,
                mCartFragment,
                mineFragment
        };
        // 添加显示第一个fragment
        getSupportFragmentManager()
                .beginTransaction()
                .add(R.id.main_container, indexFragment)
                .show(indexFragment).commit();
        tabViews.get(0).setSelected(true);
        int page = getIntent().getIntExtra("pageNo", 0);
        if (page != 0)
            changeFragmentIndex(page);

    }

    @OnClick({R.id.tab1, R.id.tab2, R.id.tab3, R.id.tab4, R.id.tab5})
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tab1:
                changeFragmentIndex(0);
                break;
            case R.id.tab2:
                changeFragmentIndex(1);
                break;
            case R.id.tab3:
                changeFragmentIndex(2);
                break;
            case R.id.tab4:
                changeFragmentIndex(3);
                break;
            case R.id.tab5:
                changeFragmentIndex(4);
                break;
        }
    }


    /**
     * 切换Fragment的下标
     */
    private void changeFragmentIndex(int currentIndex) {
        index = currentIndex;
        switchFragment();
        for (int i = 0; i < tabViews.size(); i++) {
            tabViews.get(i).setSelected(false);
        }
        tabViews.get(currentIndex).setSelected(true);
    }

    public void onEvent(UpdateCartNum updateCartNum) {
        getCartsNum();
    }

    /**
     * Fragment切换
     */
    private void switchFragment() {
        FragmentTransaction trx = getSupportFragmentManager().beginTransaction();
        trx.hide(fragments[currentTabIndex]);
        if (!fragments[index].isAdded()) {
            trx.add(R.id.main_container, fragments[index]);
        }
        trx.show(fragments[index]).commit();
        currentTabIndex = index;

        switch (index) {
            case 0:
                ((IndexFragment) fragments[0]).getNewsNum();
                break;
            case 1:
                //((ClassifyFragment) fragments[1]).refresh();
                break;
            case 2:
                break;
            case 4:
                if (member != null)
                    ((MineFragment) fragments[4]).getUserInfo();
                break;

        }

    }

    @Override
    protected void onResume() {
        super.onResume();
        if (member != null) {
            getCartsNum();
        }
    }

    //位置权限请求成功
    @Override
    public void onRequestLocPermissionSuccessed() {
        PushManager.getInstance().initialize(this.getApplicationContext(), PushService.class);
        // com.getui.demo.DemoIntentService 为第三方自定义的推送服务事件接收类
        PushManager.getInstance().registerPushIntentService(this.getApplicationContext(), PushIntentService.class);
        if (TextUtils.isEmpty(BaseApplication.getInstance().getCityName()))
            requestLocation();
    }

    @Override
    public void onLocSucceed() {
        ((IndexFragment) fragments[0]).setCity(BaseApplication.getInstance().getCityName());
    }

    @Override
    public void onLocFailed() {
        requestLocation();
    }

    @Override
    public void onRequestSdSucceed() {

    }


    private long exitTime = 0;

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) {
            if ((System.currentTimeMillis() - exitTime) > 2000) {
                Toast.makeText(mContext, "再按一次退出程序", Toast.LENGTH_SHORT).show();
                exitTime = System.currentTimeMillis();
            } else {
                EventBus.getDefault().post(new ExitApp());
                System.exit(1);
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }
}
